import { getHome } from '@/api/home';
import { Toast } from 'vant';
import { createStore } from 'vuex'
import user from './user/index'
export default createStore({
  state: {
    cartList: [],
    shopList: [],
  },
  getters: {
    totalNum(state) {
      var num = 0;
      var totalPrice = 0;
      var allSelect = true;
      state.cartList.forEach(e => {
        // if (e.is_select) {

        if (e.is_select) {
          num += e.nums;
          totalPrice += (+e.products.price) * (+e.nums);
        } else {
          allSelect = false;
        }

        // }
      });
      return { "num": num, "totalPrice": totalPrice.toFixed(2), "allSelect": allSelect };
    }
  },
  mutations: {
    addGoods(state, goods) {
      let canAdd = true;
      state.cartList.forEach(i => {
        if (i.products.id === goods.product.id) {
          canAdd = false;
          i.nums += goods.nums;
        }
      });
      if (canAdd) {
        let canShop = true;
        state.shopList.forEach(e => {
          if (e.id == goods.shop_id) {
            canShop = false;
          }
        });
        if (canShop) {
          if ("shop" in goods) {
            state.shopList.unshift({ ...goods.shop })
          }
          state.shopList.unshift({ "id": goods.shop_id })
        }
        state.cartList.unshift({ "products": goods.product, "is_select": false, "nums": 1 });

        console.log(state.cartList);
        console.log(state.shopList);
      }
    },
    //删除 没有接口好用
    delItem(state, item) {
      let a = state.cartList.findIndex(i => i.products.id == item.id);
      state.cartList.splice(a, 1);

      let empty = false;
      let index = 0;
      for (var i = 0; i < state.shopList.length; i++) {
        let qq = state.cartList.some(item => item.products.shop_id == state.shopList[i].id)
        if (!qq) {
          empty = true;
          index = i;
          break;
        }
      }
      console.log(11111, empty);
      if (empty) {
        console.log(state.shopList)
        state.shopList.splice(index, 1)
      }
    },
    changeSelect(state, a) {
      state.cartList.forEach(i => {
        i.is_select = a;
      }
      )
    },
    initCart(state, Lists) {
      state.cartList = Lists;
      // console.log(state.cartList);
    },
    initshop(state, Lists) {
      state.shopList = Lists;
    }
  },
  actions: {
    initList(context) {
      getHome({ ids: "", display: "all", token: "8d92261da8325bd3958482e3ba907b51", method: "cart.getlist" })
        .then(res => {
          context.commit("initCart", res.data.data.list)
          context.commit("initshop", res.data.data.shoplist)
        })
    },
    delItem(context, id) {
      getHome({ ids: id, token: "29313629b21f6badabd0e076ea816aad", method: "cart.del" }).then(res => {
        if (res.data.status) {
          Toast.success(res.data.msg);
          context.dispatch("initList")
        }
      })
    }
  },
  modules: {
    user
  }
})
